package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.service.IdService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service(version = "1.0.0")  //申明是一个dubbo服务
public class SoundApiImpl implements SoundApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService idService;


    /**
     * 功能描述: saveSound    保存声音
     */
    @Override
    public String saveSound(Sound sound) {
        //如果sound对象的id为空,则返回null
        if (sound.getUserId() == null) {
            return null;
        }
        sound.setId(ObjectId.get());
        sound.setCreated(System.currentTimeMillis());

        //自增长id
        sound.setSid(this.idService.createId("sound", sound.getId().toString()));
        this.mongoTemplate.save(sound);
        return sound.getId().toString();
    }

    @Override
    public List<Sound> receiveSound() {
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.sample(10)
        );

        AggregationResults<Sound> soundList = this.mongoTemplate.aggregate(agg, "sound", Sound.class);
        return soundList.getMappedResults();
    }

    @Override
    public boolean removeSound(Sound sound) {
        DeleteResult result = this.mongoTemplate.remove(Query.query(Criteria.where("sid").is(sound.getSid())), Sound.class);
        return result.getDeletedCount() > 0;
    }
}
